package com.example.cqh_votesys.sevice.impl;

import com.example.cqh_votesys.constant.MessageConstant;
import com.example.cqh_votesys.controller.LoginController;
import com.example.cqh_votesys.exception.LoginException;
import com.example.cqh_votesys.mapper.UserMapper;
import com.example.cqh_votesys.pojo.pojo.User;
import com.example.cqh_votesys.sevice.LoginService;
import com.example.cqh_votesys.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @Author: pollux
 * @CreateTime: 2024-06-30
 * @Description: 登录业务类
 * @Version: 1.0
 */

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;


    /**
     *
     * @description: 登录接口
     * @param user 用户实体类
     * @return: com.example.cqh_votesys.pojo.result.Result
     * @author: pollux
     * @date: 2024/6/30 14:18
     */
    @Override
    public String login(User user) {
        //通过邮箱查询这个用户的密码
        User temp =  userMapper.getUserByEmail(user.getEmail());

        //账号不存在
        if (temp == null){
            throw new LoginException(MessageConstant.ACCOUNT_NO_EXIST);
        }
        //还原密码
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        if (!temp.getPassword().equals(user.getPassword())){
            //条件取反，密码不一致就抛出异常
             throw new LoginException(MessageConstant.PASSWORD_UNCORRECT);
        }

        //来到这里就是密码正确，就获取token，修改这条数据库的token字段
        //无语了，jwt 0.12.3版本 长度必须达到256bits才行
        String jwt = JwtUtil.createJwt("22级软件b班陈全焕jwtjwtjwtjwtjwtjwt");

        //修改这条记录的token
        temp.setToken(jwt);
        userMapper.update(temp);

        //将token返回
        return jwt;
    }
}











